<?php

/**
 * user actions.
 *
 * @package    sfwixet
 * @subpackage user
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class userActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {

	//sfContext::getInstance()->getI18n()->__('hola');
  	//Los action no tiene helpers de esos
	try{
		$profile = Doctrine::getTable("Profile")->find($request->getParameter("id",$this->getUser()->getId()));
		$user = $profile->getUser();
		$data = $user->toArray();
		$data['theme'] = $user->getTheme()->toArray();
		$data['language'] = $user->getLanguage()->toArray();
		$data['font'] = $user->getFont()->toArray(); 
		$data['city'] = $profile->getCity()->toArray();
		unset($data['algorithm'],$data['salt'],$data['password'],$data['is_super_admin'],$data['main_album'],$data['main_group']);
		$data['birthday'] = $profile->getBirthday();
	}catch(Exception $e){
		$data = array("error"=>true, "message"=>$e->getMessage());
	}
	echo json_encode($data);
	return sfView::NONE;
  }
  
  public function executeWhoAmI(sfWebRequest $request){
  	$this->forward('user', 'index');
  }
  
  public function executeUpdate(sfWebRequest $request)
  {
	
  	
  	try{
  		$result = array("error"=>false);
		$user = $this->getUser()->getGuardUser();
	
		if($request->getParameter("firstName"))
			$user->setFirstName($request->getParameter("firstName"));
			
		if($request->getParameter("lastName"))
			$user->setLastName($request->getParameter("lastName"));
			
		if($request->getParameter("secondLastName"))
			$user->setSecondLastName($request->getParameter("secondLastName"));
			
		if($request->getParameter("birthday"))
			$user->getProfile()->setBirthday($request->getParameter("birthday"));
			
		if(is_numeric($request->getParameter("city")))
			$user->getProfile()->setCityId($request->getParameter("city"));
			
		if(is_numeric($request->getParameter("theme")))
			$user->setThemeId($request->getParameter("theme"));
			
		if(is_numeric($request->getParameter("font")))
			$user->setFontId($request->getParameter("font"));
			
		if($request->getParameter("textcolor"))
			$user->setTextColor($request->getParameter("textcolor"));
			
		if($request->getParameter("language")){
			try{
				$lang = Doctrine::getTable("language")->findByLanguageCode($request->getParameter("language"))->getFirst();
				$lang->getLanguageCode();
				$user->setLanguage($lang);
				$this->getResponse()->setCookie('language', $lang->getLanguageCode());
				$this->getUser()->setCulture($lang->getLanguageCode());
			}catch(Exception $e){
				$result['warning'] = $e->getMessage();
			}
		}
			
		$user->save();
		echo json_encode($result);
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>$e->getMessage()));
  	}
	return sfView::NONE;
  }
  
  public function executeFriendList(sfWebRequest $request)
  {
  		$friends = array();
  		foreach($this->getUser()->getFriendList()->getUsers() as $user)
  		{
  			$friend = array();
  			$friend['firstName'] = $user->getFirstName();
  			$friend['lastName'] = $user->getLastName();
  			$friend['secondLastName'] = $user->getSecondLastName();
  			$friend['id'] = $user->getId();
  			$friends[] = $friend;
  		}

  		echo json_encode($friends);
  		  	
  		return sfView::NONE;
  }
  
  public function executeAlbumsList(sfWebRequest $request)
  {
  		$albums = array();
  		$album = new Album();
  		$album->setAlbumId(1);
  		$album->setOwnerId(1);
  		//$album->setParentId(null);
  		$album->setName("Album guay");
  		
  		$albums[] = $album;
  		
  		$album = new Album();
  		$album->setAlbumId(2);
  		$album->setOwnerId(1);
  		$album->setParentId(1);
  		$album->setName("Album subguay");
  		
  		$albums[] = $album;
  		
  		$album = new Album();
  		$album->setAlbumId(3);
  		$album->setOwnerId(1);
  		//$album->setParentId(1);
  		$album->setName("Otro album");
  		
  		
  		
  		$this->list = $albums;
  }
  
  public function executeGetMyAclGroupList(sfWebRequest $request){
  
  	echo json_encode($this->getUser()->getGuardUser()->getMyAclGroups()->toArray());
  	return sfView::NONE;
  }
  
  public function executeGetAclGroup(sfWebRequest $request){
  		if($id = $request->getParameter("id")){
			$group = Doctrine::getTable("AclGroup")->find($id);
			if($group->getOwnerId() == $this->getUser()->getId()){
				$groupArr = $group->toArray();
				$groupArr['users'] = array();
				foreach($group->getUsers() as $user){
					$userArr = array();
					$userArr['id'] = $user->getId();
					$userArr['firstName'] = $user->getFirstName();
					$userArr['lastName'] = $user->getLastName();
					$userArr['secondLastName'] = $user->getSecondLastName();
					$userArr['email'] = $user->getEmailAddress();
					$groupArr['users'][] = $userArr;
				}
				
				foreach($group->getPhotos() as $photo){
					$photoArr = array();
					$photoArr['id'] = $photo->getPhotoId();
					$photoArr['title'] = $photo->getTitle();
					$photoArr['permissions'] = $photo->getPermissionsForGroup($group);
					$groupArr['photos'][] = $photoArr;
				}
				
				foreach($group->getAlbums() as $album){
					$albumArr = array();
					$albumArr['id'] = $album->getAlbumId();
					$albumArr['title'] = $album->getName();
					$albumArr['permissions'] = $album->getPermissionsForGroup($group);
					$groupArr['albums'][] = $albumArr;
				}
				
				foreach($group->getProfiles() as $profile){
					$profileArr = array();
					$profileUser = $profile->getUser();
					$profileArr['id'] = $profile->getUserId();
					$profileArr['title'] = $profileUser->getFirstName()." ".$profileUser->getLastName()." ".$profileUser->getSecondLastName();
					$profileArr['permissions'] = $profile->getPermissionsForGroup($group);
					$groupArr['profiles'][] = $profileArr;
				}
				
				echo json_encode($groupArr);
			}else echo json_encode(array("error"=>true,"message"=>_("Permission denied")));
  		}else echo json_encode(array("error"=>true,"message"=>_("Please specify a group id")));
  	
  	return sfView::NONE;
  }
  
  public function executeNewAclGroup(sfWebRequest $request){
  	if($request->getParameter("name"))
  	{
  		$group = new AclGroup();
  		$group->setGroupName($request->getParameter("name"));
  		$group->setOwnerId($this->getUser()->getId());
  		$group->save();
  		
  		$mainAlbumId = $this->getUser()->getGuardUser()->getMainAlbumId();
  		
		$users = json_decode($request->getParameter("users","[]"));
					
  		foreach($users as $userId){
			//Check if the user is friend
			$q = Doctrine_Query::create()
				->select('a.user_id')
				->from('aclUsersGroups a')
				->where('a.user_id = ? and a.group_id = ?',array($userId,$mainAlbumId));
			if($q->execute()->count() > 0)
			{
			   $newMember = new AclUsersGroups();
			   $newMember->setGroupId($group->getGroupId());
			   $newMember->setUser_id($userId);
			   $newMember->save();
			}
		}
		//Add default permission to profile
		$profile = new AclProfileGroup();
		$profile->setProfileId($this->getUser()->getId());
		$profile->setGroupId($group->getGroupId());
		$profile->setReadGranted(true);
		$profile->setReadDenied(false);
		$profile->setWriteGranted(true);
		$profile->setWriteDenied(false);
		$profile->save();
		//
		 echo json_encode(array("error"=>false));
  	}else echo json_encode(array("error"=>true,"message"=>_("Please specify a group name")));
  	return sfView::NONE;
  }
  
  public function executeUpdateGroup(sfWebRequest $request){
  	if($id = $request->getParameter("id"))
  	{
  		$group = Doctrine::getTable("AclGroup")->find($id);
		if($group instanceof AclGroup && $group->getOwnerId() == $this->getUser()->getId()){
			if($group->getGroupId() != $this->getUser()->getGuardUser()->getMainGroupId())
			{
				if($name = $request->getParameter("name"))
					$group->setGroupName($name);
					
				if($users = $request->getParameter("users")){
					$users = json_decode($users);
					$mainAlbumId = $this->getUser()->getGuardUser()->getMainAlbumId();
					if(is_array($users)){
						$friendList = $this->getUser()->getFriendList();
						//Reset the group list
							$q = Doctrine_Query::create()
								->delete('aclUsersGroups a')
								->where('a.group_id = ?',$group->getGroupId())
								->execute();
						foreach($users as $userId){
							//Check if the user is friend

							$q = Doctrine_Query::create()
								->select('a.user_id')
								->from('aclUsersGroups a')
								->where('a.user_id = ? and a.group_id = ?',array($userId,$mainAlbumId));

							if($q->execute()->count() > 0)
							{
							   $newMember = new AclUsersGroups();
							   $newMember->setGroupId($group->getGroupId());
							   $newMember->setUser_id($userId);
							   $newMember->save();
							}
						}
						echo json_encode(array("error"=>false));
					}
				}
				
			}else echo json_encode(array("warning"=>true,"message"=>_("You cannot modify your main group")));
			
			if($request->getParameter("permissions")){
				$permissions = json_decode($request->getParameter("permissions"));
				$profiles = $permissions->profiles;
				foreach($profiles as $profile){
					//At the moment the users only have one profile
					if($profile->id == $this->getUser()->getId()){
						$permission = Doctrine::getTable("AclProfileGroup")->find(array($profile->id,$group->getGroupId()));
						$permission->setReadGranted($profile->readGranted);
						$permission->setReadDenied($profile->readDenied);
						$permission->setWriteGranted($profile->writeGranted);
						$permission->setWriteDenied($profile->writeDenied);
						$permission->save();
					}
				}
				
				$albums = $permissions->albums;
				foreach($albums as $album){
					try{
						$realAlbum = Doctrine::getTable("Album")->find($album->id);
						if($realAlbum->getOwnerId() == $this->getUser()->getId()){
							$permission = Doctrine::getTable("AclAlbumGroup")->find(array($album->id,$group->getGroupId()));
							$permission->setReadGranted($album->readGranted);
							$permission->setReadDenied($album->readDenied);
							$permission->setWriteGranted($album->writeGranted);
							$permission->setWriteDenied($album->writeDenied);
							$permission->save();
						}
					}catch(Exception $e){
						//Not allowed to modify album permission
					}
				}
				
				$photos = $permissions->photos;
				foreach($photos as $photo){
					try{
						$realPhoto = Doctrine::getTable("Photo")->find($photo->id);
						if($realPhoto->getOwnerId() == $this->getUser()->getId()){
							$permission = Doctrine::getTable("AclPhotoGroup")->find(array($photo->id,$group->getGroupId()));
							$permission->setReadGranted($photo->readGranted);
							$permission->setReadDenied($photo->readDenied);
							$permission->setWriteGranted($photo->writeGranted);
							$permission->setWriteDenied($photo->writeDenied);
							$permission->save();
						}
					}catch(Exception $e){
						//Not allowed to modify album permission
					}
				}
			}
		}else echo json_encode(array("error"=>true,"message"=>_("Permission denied")));
  	}else echo json_encode(array("error"=>true,"message"=>_("Please specify a group id")));
  	return sfView::NONE;

  }
  
  public function executeUserActivity(sfWebRequest $request){
  	
  	return sfView::NONE;
  }
  
  public function executeIgnoreFriendRequest(sfWebRequest $request){
  	$friendRequest = Doctrine::getTable("FriendRequest")->find(array($request->getParameter("id",0),$this->getUser()->getId()));
  	if($friendRequest instanceof FriendRequest){
  		//Only null status are notificated to user
  		$friendRequest->setStatus(1);
  		$friendRequest->save();
  		echo json_encode(array("error"=>false));
  	}else{
  		echo json_encode(array("error"=>true,"message"=>_("Invalid friend request")));
  	}
  	return sfView::NONE;
  }
  
  public function executeAcceptFriendRequest(sfWebRequest $request){
  	$friendRequest = Doctrine::getTable("FriendRequest")->find(array($request->getParameter("id",0),$this->getUser()->getId()));
  	if($friendRequest instanceof FriendRequest){
  		$friend = Doctrine::getTable("sfGuardUser")->find($request->getParameter("id"));
  		$this->getUser()->getGuardUser()->getMainGroup()->addUser($friend);
  		$friend->getMainGroup()->addUser($this->getUser());
  		$friendRequest->delete();
  		
  		$this->getUser()->getGuardUser()->touch();
  		$friend->touch();
  		//Make xmpp friends
  		$ch = curl_init();
  		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  		$url="http://127.0.0.1:9090/plugins/rosterManager/rostermanager?type=create&username=".$this->getUser()->getGuardUser()->getUsername()."&jid=".$friend->getUsername()."@wixet.com&secret=".sfConfig::get('sf_openfire_secret');
        curl_setopt($ch, CURLOPT_URL,$url);
        $res11 = json_decode(curl_exec ($ch));
        
  		$url="http://127.0.0.1:9090/plugins/rosterManager/rostermanager?type=modify&username=".$this->getUser()->getGuardUser()->getUsername()."&jid=".$friend->getUsername()."@wixet.com&sub=both&secret=".sfConfig::get('sf_openfire_secret');
        curl_setopt($ch, CURLOPT_URL,$url);
        $res12 = json_decode(curl_exec ($ch));
        
        //The other hand
        $url="http://127.0.0.1:9090/plugins/rosterManager/rostermanager?type=create&username=".$friend->getUsername()."&jid=".$this->getUser()->getGuardUser()->getUsername()."@wixet.com&secret=".sfConfig::get('sf_openfire_secret');
        curl_setopt($ch, CURLOPT_URL,$url);
        $res21 = json_decode(curl_exec ($ch));
        
        $url="http://127.0.0.1:9090/plugins/rosterManager/rostermanager?type=modify&username=".$friend->getUsername()."&jid=".$this->getUser()->getGuardUser()->getUsername()."@wixet.com&sub=both&secret=".sfConfig::get('sf_openfire_secret');
        curl_setopt($ch, CURLOPT_URL,$url);
        $res22 = json_decode(curl_exec ($ch));
        curl_close($ch);
        
                         
  		echo json_encode(array("error"=>false,"xmpp_error"=>$res11->error || $res12->error || $res21->error || $res22->error));
  	}else{
  		echo json_encode(array("error"=>true,"message"=>_("Invalid friend request")));
  	}
  	return sfView::NONE;
  }
  
  public function executeFriendRequest(sfWebRequest $request){
  	try{
  		if($request->getParameter("id") == $this->getUser()->getId()) throw new Exception(_("You can not send friend request yourself"));
  		$this->getUser()->getGuardUser()->friendRequest(Doctrine::getTable("sfGuardUser")->find($request->getParameter("id")));
  		echo json_encode(array("error"=>false));
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>$e->getMessage()));
  	}
  	return sfView::NONE;
  }
  
  public function executeGetNewPhotoComments(sfWebRequest $request){
  	$q = Doctrine_Query::create()
    ->select('p.photo_id')
    ->addSelect('COUNT(p.photo_id) as count')
    ->from('PhotoCommentNotification p')
    ->groupBy('p.photo_id');
	

  	$photoComments = $q->execute();
  	echo json_encode($photoComments->toArray());
  	return sfView::NONE;
  }
  
  public function executeGetNewPhotoTags(sfWebRequest $request){

  	echo json_encode(Doctrine::getTable("PhotoTagNotification")->findByUserId($this->getUser()->getId())->toArray());
  	return sfView::NONE;
  }
  
  public function executeIsFriend(sfWebRequest $request){
    $friend = Doctrine::getTable("sfGuardUser")->find($request->getParameter("id"));
    echo json_encode($friend->isFriend($this->getUser()));
	return sfView::NONE;

  }

  
  public function executeNews(sfWebRequest $request){
  	$type = $request->getParameter("type","friends");
  	$list = array();
  	if($type == "friends"){		
  			$list = $this->getUser()->getFriendNews();
  			for($i=0;$i<count($list);$i++){
  				
  			}	
  	}else if($type == "photos"){
  			$list = $this->getUser()->getGuardUser()->getPhotoNews();
  		
  	}
  	echo json_encode($list);
  	return sfView::NONE;
  	
  }
  
  public function executeEmoticonList(sfWebRequest $request){
    echo json_encode($this->getUser()->getGuardUser()->getEmoticons()->toArray(false));
	return sfView::NONE;  	
  }
  
  public function executeSoundList(sfWebRequest $request){
  	$q = Doctrine_Query::create()
    ->from('SoundUser su')
    ->where('su.user_id = ?',$this->getUser()->getId())
    ->orderBy('su.times_used')
    ->limit(20);
    
    $sounds = array();
    foreach($q->execute() as $soundUser){
    	$element = $soundUser->getSound()->toArray(false);
    	unset($element['uploader_id']);
    	$sounds[]= $element;
    }
    echo json_encode($sounds);
	return sfView::NONE;  	
  }
  
  public function executeSetMainPhoto(sfWebRequest $request){
  	try{
  		$photo = Doctrine::getTable("Photo")->find($request->getParameter("id"));
  		$user = $this->getUser()->getGuardUser(); 
  		$user->setFace($photo);
  		$user->save();
  		echo json_encode(array("error"=>false));
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>$e->getMessage()));
  	}
  	return sfView::NONE; 
  }
}
